package com.atguigu.gulimall.order.interceptor;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@RestController
public class AlipayedInterceptor {
    @Resource
    AlipayTemplate alipayTemplate;
    @Resource
    OrderService orderService;

    @PostMapping("/payed/ali/notify")
    public String aliNotify(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException {
        //先进行验签
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
                alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名

        if(signVerified){
            //验签成功进行确认订单
            try{
                String result = orderService.handlePayResult(vo);
                log.info("订单支付成功");
                System.out.println("-----------------------------------------------");
                return result;
            }catch (Exception e){
                log.info("订单支付失败");
                return "error";
            }
        }else {
            log.info("订单支付失败");
            return "error";
        }
    }
}
